package com.cy.pj.common.HikariCP.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultDataSource implements GoodsDao {
    @Autowired
    private DataSource dataSource;

    Map<String,Object> rowMap(ResultSet rs, ResultSetMetaData rsmd) throws SQLException {
        Map<String,Object> map= new HashMap<>();
        for(int i=1;i<=rsmd.getColumnCount();i++){
            map.put(rsmd.getColumnName(i),rs.getObject(i));
        }
        return map;
    }

    void fn(ResultSet rs,Statement stat,Connection conn){
        if(rs != null) try { rs.close(); } catch (SQLException e) {}
        if(stat != null) try { stat.close(); } catch (SQLException e) {}
        if(conn != null) try {conn.close(); } catch (SQLException e) {}
    }
    private static final Logger log = LoggerFactory.getLogger(DefaultDataSource.class);
    @Override
    public List<Map<String, Object>> findData() {
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        String sql = "select * from tb_goods";

//        1.创建连接
        try {
            conn = dataSource.getConnection();
//        2.创建连接对象
            stat = conn.createStatement();
//        3.写Sql语句
            rs = stat.executeQuery(sql);
//        4.处理结果
            List<Map<String,Object>> list = new ArrayList();
            while(rs.next()){
//                Map<String,Object> map = new HashMap<>();
//                map.put("id", rs.getInt("id"));
//                map.put("name", rs.getString("name"));
//                map.put("remark", rs.getString("remark"));
//                map.put("createdTime", rs.getTimestamp("createdTime"));
//                list.add(map);
                list.add(rowMap(rs, rs.getMetaData()));
            }
            return list;
        } catch (SQLException e) {
//            e.printStackTrace();
//            return null;
            log.error("异常，{}",e.getMessage());
            throw new RuntimeException(e.getMessage());
        }finally{
//            if(rs != null) try { rs.close(); } catch (SQLException e) {}
//            if(stat != null) try { stat.close(); } catch (SQLException e) {}
//            if(conn != null) try {conn.close(); } catch (SQLException e) {}
            fn(rs,stat,conn);
        }
    }
}
